package cn.edu.nit.sys.controller;

import cn.edu.nit.sys.dto.UserDTO;
import cn.edu.nit.sys.mapper.UserMapper;
import cn.edu.nit.sys.service.IndexService;
import cn.edu.nit.sys.utils.R;
import cn.edu.nit.sys.vo.ChangeAvatarVO;
import cn.edu.nit.sys.vo.UserVO;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @Author xiaobai
 * @Date 2022/9/4 12:56
 * @Version 1.0.0
 */
@RestController
public class IndexController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IndexService indexService;

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    public R login(@RequestBody UserVO userVO, HttpServletRequest request, HttpServletResponse response) {
        if(!"app".equals(userVO.getOs())) {
            String uuid = redisTemplate.opsForValue().get(request.getHeader("uuid"));
            if(ObjectUtils.isEmpty(uuid)) {
                return R.error("验证码已过期");
            }
            if(!uuid.equals(userVO.getCode())) {
                return R.error("验证码错误");
            }
        }
        return indexService.login(userVO, response);
    }

    @GetMapping("/getPosition")
    public R getDept(){
        return indexService.getPosition();
    }

    @PostMapping("/user/avatar")
    public R changeAvatar(@RequestBody ChangeAvatarVO changeAvatarVO) {
        Integer changeAvatar = userMapper.changeAvatar(changeAvatarVO.getId(), changeAvatarVO.getSourUrl());
        return changeAvatar > 0 ? R.ok("修改成功") : R.error("修改失败");
    }

    @GetMapping("/count")
    public R countData() {
        return indexService.getCount();
    }

    @GetMapping("/code/{phone}")
    public R sendPhoneCode(@PathVariable("phone") String phone) {
        return indexService.sendPhoneCode(phone);
    }

    @PostMapping("/code/verify")
    public R verifyCode(@RequestBody Map<String, String> params) {
        return indexService.verifyCode(params);
    }

}
